package com.chcit.mobile.mvp.receive.fragment.pack.child;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chcit.custom.view.toolbar.CommonToolbar;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.SupportToolbarFragement;
import com.chcit.mobile.common.DataKeys;
import com.chcit.mobile.di.component.DaggerReceiveComponent;
import com.chcit.mobile.di.module.ReceiveModule;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.receive.Entity.AsnPackageBean;
import com.chcit.mobile.mvp.receive.Entity.ImageUrl;
import com.chcit.mobile.mvp.receive.adpter.ImageSelectGridAdapter;
import com.chcit.mobile.mvp.receive.contract.ReceiveContract;
import com.chcit.mobile.mvp.receive.presenter.ReceivePresenter;
import com.jess.arms.di.component.AppComponent;
import com.luck.picture.lib.PictureSelectionModel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.xuexiang.xui.widget.imageview.preview.PreviewBuilder;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;

public class ImagePickFragment extends SupportToolbarFragement<ReceivePresenter> implements ImageSelectGridAdapter.OnAddPicClickListener, ReceiveContract.View {

    @BindView(R.id.recycler_iamge_pick)
    RecyclerView recyclerView;
    @BindView(R.id.common_toolbar)
    CommonToolbar mCommonToolbar ;
    private ImageSelectGridAdapter mAdapter;
    private List<ImageUrl> mSelectList = new ArrayList<>();
    private List<LocalMedia> mSelectedImage = new ArrayList<>();
    AsnPackageBean asnPackageBean;
    private static final int REQUEST_CODE_CHOOSE_PHOTO_SHOOT = 88;
    private GridLayoutManager manager;
    private MenuTypeEnum type;
    public static ImagePickFragment newInstance(AsnPackageBean asnPackageBean, MenuTypeEnum typeEnum) {
        ImagePickFragment imagePickFragment =  new ImagePickFragment(typeEnum);
        imagePickFragment.asnPackageBean = asnPackageBean;
        return imagePickFragment;
    }

    public ImagePickFragment(MenuTypeEnum type) {

    }

    protected void initViews() {
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            Bundle bundle = new Bundle();
            bundle.putInt(DataKeys.ATTACHMENT_COUNT.name(),mSelectList.size());
            findFragment(FirstPagerFragment.class).onFragmentResult(FirstPagerFragment.REQUEST_CODE,RESULT_OK,bundle);
            pop();
        });
        manager = new GridLayoutManager(getActivity(), 4, RecyclerView.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(mAdapter = new ImageSelectGridAdapter(getActivity(), this));
//        mSelectList.add(new ImageUrl(23123,"https://raw.githubusercontent.com/JessYanCoding/MVPArms/master/image/hui_cai_fu_logo.png"));
        mAdapter.setSelectList(mSelectList);
        mAdapter.setSelectMax(8);
        mAdapter.setOnItemClickListener((position, v) -> {
            computeBoundsBackward(position);
//            PictureSelector.create(this).themeStyle(R.style.XUIPictureStyle_Custom).
//                    openExternalPreview(position, mSelectList);
            PreviewBuilder.from(this)
                    .setImgs(mSelectList)
                    .setCurrentIndex(position)

                    .setSingleFling(true)
                    .setProgressColor(R.color.xui_config_color_main_theme)
                    .setType(PreviewBuilder.IndicatorType.Number)
                    .start();
        });
        mAdapter.setOnDeletePicClickListener((position,item)->{
                if(position>-1&&mSelectList.size()>position){
                    mPresenter.deleteImage(String.valueOf(item.getAttachmentId()),()->{
                        mSelectList.remove(position);
                        mAdapter.notifyDataSetChanged();
//                        mAdapter.notifyItemRangeChanged(position, mSelectList.size());
                        XToast.success(mContext,"删除成功！").show();
                    });
                }

        });
        mPresenter.queryImageUrls(asnPackageBean.getAsnId(),list->{
            mSelectList.addAll(list);
//            mAdapter.setSelectList(mSelectList);
            mAdapter.notifyDataSetChanged();
        });

    }
    /**
     * 查找信息
     * 从第一个完整可见item逆序遍历，如果初始位置为0，则不执行方法内循环
     */
    private void computeBoundsBackward(int firstCompletelyVisiblePos) {
        for (int i = firstCompletelyVisiblePos; i < mSelectList.size(); i++) {
            View itemView = manager.findViewByPosition(i);
            Rect bounds = new Rect();
            if (itemView != null) {
                ImageView imageView = itemView.findViewById(R.id.iv_select_pic);
                imageView.getGlobalVisibleRect(bounds);
            }
            mSelectList.get(i).setBounds(bounds);
        }
    }
    @Override
    public void onAddPicClick() {
        getPictureSelector(ImagePickFragment.this)
                .selectionMedia(mSelectedImage)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    mSelectedImage= PictureSelector.obtainMultipleResult(data);
                    mPresenter.uploadImage(asnPackageBean.getAsnId(),Arrays.asList(mSelectedImage.get(0).getPath()),(item)->{
//                        ImageUrl imageUrl = new ImageUrl();
//                        imageUrl.setTextMsg(mSelectedImage.get(0).getPath());
//                        imageUrl.setAttachmentId();
                        mSelectList.add(item);
                        mAdapter.notifyDataSetChanged();
                        mSelectedImage.clear();
                        XToast.success(mContext,"上传成功").show();
                    });
//                     Observer<List<LocalMedia>>
                    //fromIterable接收一个Iterable，每次发射一个元素（与for循环效果相同）
                    //interval定时器，间隔1秒发射一次
//                    Observable<Long> timerObservable = Observable.interval(1000, TimeUnit.MILLISECONDS);
                    mAdapter.notifyDataSetChanged();
                    break;
                case REQUEST_CODE_CHOOSE_PHOTO_SHOOT:
                /*    mSelected = Matisse.obtainResult(data);
                    if(mSelected!=null&&mSelected.size()>0){
                        File imageFile = FileUtil.getFileFromUri(mSelected.get(0),getContext());
                        XToast.info(getContext(),imageFile.getPath(),-1).show();

                    }*/
                    break;
                default:
                    break;
            }

        }
    }
    /**
     * 获取图片选择的配置
     *
     * @param fragment
     * @return
     */
    private  PictureSelectionModel getPictureSelector(Fragment fragment) {
        return PictureSelector.create(fragment)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.XUIPictureStyle_Custom)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(false)
                .compress(true)
                .previewEggs(true);
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerReceiveComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .receiveModule(new ReceiveModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_image_pick, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.setTitleText("图片管理");
        initViews();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public <E> void updateContentList(List<E> receiveBeans) {

    }

    @Override
    public <T extends View> T getViewByTag(int i) {
        return null;
    }

    @Override
    public void showMessage(@NonNull String message) {

    }
/*

    private void selectIcon(){
//        MediaStoreCompat mediaStoreCompat = new MediaStoreCompat(this.getActivity(),this);
//        mediaStoreCompat.setCaptureStrategy(new CaptureStrategy(true,"PhotoPicker"));
//        mediaStoreCompat.dispatchCaptureIntent(mContext,REQUEST_CODE_CHOOSE_PHOTO_SHOOT);
        //因为是指定Uri所以onActivityResult中的data为空 只能再这里获取拍照的路径
//        String currentPhotoPath = mediaStoreCompat.getCurrentPhotoPath();
        //返回图片路径名
//        getActivity().getCurrentPhotoPath(currentPhotoPath);
        Matisse
                .from(this)
                .choose(MimeType.ofImage(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(
                        new CaptureStrategy(true, "com.chcit.mobile.app.ImageFileProvider", "glyy"))
                .maxSelectable(1)
//                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                .gridExpectedSize(
//                        getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideImageEngine())
                .setOnSelectedListener((uriList, pathList) -> {
                    XLog.e("onSelected", "onSelected: pathList=" + pathList);
                })
                .showSingleMediaType(true)
                .originalEnable(true)
                .maxOriginalSize(10)
                .autoHideToolbarOnSingleTap(true)
                .setOnCheckedListener(isChecked -> {
                    XLog.e("isChecked", "onCheck: isChecked=" + isChecked);
                })
                .forResult(REQUEST_CODE_CHOOSE_PHOTO_SHOOT);
 */
/*       Matisse
                .from(this)
                //选择视频和图片
//                .choose(MimeType.ofAll())
                //选择图片
                .choose(MimeType.ofImage())
                //选择视频
//                .choose(MimeType.ofVideo())
                //自定义选择选择的类型
//                .choose(MimeType.of(MimeType.JPEG,MimeType.AVI))
                //是否只显示选择的类型的缩略图，就不会把所有图片视频都放在一起，而是需要什么展示什么
                .showSingleMediaType(true)
                //这两行要连用 是否在选择图片中展示照相 和适配安卓7.0 FileProvider
                .capture(true)
                .captureStrategy(new CaptureStrategy(true,"PhotoPicker"))
                //有序选择图片 123456...
                .countable(true)
                //最大选择数量为9
                .maxSelectable(1)
                //选择方向
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                //界面中缩略图的质量
                .thumbnailScale(0.8f)
                //蓝色主题
                .theme(R.style.Matisse_Zhihu)
                //黑色主题
//                .theme(R.style.Matisse_Dracula)
                //Glide加载方式
                .imageEngine(new GlideEngine())
                //Picasso加载方式
//                .imageEngine(new PicassoEngine())
                //请求码
                .forResult(REQUEST_CODE_CHOOSE_PHOTO_SHOOT);*//*

    }

*/
    @Override
    public boolean onBackPressedSupport() {
        mCommonToolbar.getLeftMenuView(0).performClick();
        return true;
    }

}
